package http.aio;

import http.HttpRequest;
import http.HttpResponse;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;

/**
 * @author fengbo
 * @version 1.0.0
 * @date 2018/12/5 15:06
 * @since JDK 1.8
 */
public class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel channel;

    public ReadHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer integer, ByteBuffer byteBuffer) {
        byteBuffer.flip();
        byte[] message = new byte[byteBuffer.remaining()];
        byteBuffer.get(message);
        HttpRequest request = new HttpRequest(new String(message, Charset.forName("utf-8")));
        HttpResponse response = new HttpResponse(request.getUrl());
        byte[] headerArr = response.getHeader().getBytes();
        byte[] bodyArr = response.getBody();
        ByteBuffer writeBuf = ByteBuffer.allocate(headerArr.length + bodyArr.length);
        writeBuf.put(headerArr);
        writeBuf.put(bodyArr);
        channel.write(writeBuf, writeBuf, new WriteHandler(channel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer byteBuffer) {
    }
}
